import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection  import GridSearchCV
from sklearn.metrics import mean_squared_error ,mean_absolute_error ,r2_score
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')

#准备数据
data = {
    'Year': [2018, 2019, 2020, 2021, 2022, 2023],
    'Cats': [4064, 4412, 4862, 5806, 6536, 6980],  # 宠物猫数量（万只）
    'Dogs': [5085, 5503, 5222, 5429, 5119, 5175],  # 宠物狗数量（万只）
    'GDP_Per_Capita': [90.03, 98.65, 101.36, 114.92, 120.47, 126.06],  # 人均GDP（万亿）
    'Urbanization_Rate': [0.5958, 0.6060, 0.6389, 0.6472, 0.6522, 0.6616],  # 城镇化率
    'Total_Population': [13.9538, 14.0005, 14.435, 14.126, 14.1175, 14.0967],  # 总人口（百万人）
    'Cat_Market_Size': [652, 780, 884, 1060, 1231, 1305],  # 猫的市场规模（亿元）
    'Dog_Market_Size': [1056, 1244, 1180, 1430, 1475, 1488],  # 狗的市场规模（亿元）
    'Cat_Annual_Consumption': [3117, 1768, 1818, 1826, 1883, 1870],  # 一只猫年均消费金额 （元）
    'Dog_Annual_Consumption': [4723, 2261, 2262, 2634, 2282, 2875]  # 一只狗年均消费金额（元）
    # 可以添加更多宠物类型的数据
}
#创建数据框
df = pd.DataFrame(data)
#特征数量和目标变量
#对于宠物猫模型的构建
x_cat = df[['Year','GDP_Per_Capita','Urbanization_Rate','Total_Population',
           'Cat_Market_Size','Cat_Annual_Consumption']]
y_cat = df['Cats']

#对于宠物狗的模型构建
x_dog = df[['Year','GDP_Per_Capita','Urbanization_Rate','Total_Population',
           'Dog_Market_Size','Dog_Annual_Consumption']]
y_dog = df['Dogs']

#设置随机森林模型的超参数网格
param_grid ={
    'n_estimators':[50,100,200],        #森林的树木数量
    'max_depth':[5,10,15,None],         #树的最大深度
    'min_sample_split':[2,5,10],        #结点分割的最小样本数
    'min_sample_leaf':[1,2,4],          #叶子结点的最小样本数
    'max_features':['auto','sqrt','log2']    #每颗树考虑的最大特征数
}
#创建随机森林模型
cat_model = RandomForestRegressor (random_state=42)
dog_model = RandomForestRegressor (random_state=42)
#使用GridSearchCV进行超参数优化宠物猫模型
cat_grid_search = GridSearchCV(estimator=cat_model,param_grid=param_grid,
               cv=3,scoring='neg_mean_squared_error',verbose=0,n_jobs=-1)
cat_grid_search.fit(x_cat,y_cat)
best_cat_model = cat_grid_search.best_estimator_

#使用GridSearchCV进行超参数优化宠物狗模型
dog_grid_search = GridSearchCV(estimator=dog_model,param_grid=param_grid,
               cv=3,scoring='neg_mean_squared_error',verbose=0,n_jobs=-1)
dog_grid_search.fit(x_dog,y_dog)
best_dog_model = dog_grid_search.best_estimator_

#输出最佳超参数
print("\n最佳参数-宠物猫模型：")
print(cat_grid_search.best_params_)
print("\n最佳超参数-宠物狗模型：")
print(dog_grid_search.best_params_)

#预测未来2024年至2026年的趋势
future_years = [2024,2025,2026]

#使用线性代数回归预测未来值
def predict_future_features(df, future_years, features):
    predictions = {}
    for feature in features:
        x = df[['Year']]
        y = df[feature]
        model = LinearRegression()
        model.fit(x, y)  # 注意：这里存在数据泄露的风险，但在模拟中可以接受
        future_values = model.predict(pd.DataFrame({'Year': future_years}))
        predictions[feature] = future_values
    return predictions

#预测所需要的数据
cat_future_data = ['GDP_Per_Capita','Urbanization_Rate',
                   'Total_Population','Cat_Market_Size','Cat_Annual_Consumption']
dog_future_data = ['GDP_Per_Capita','Urbanization_Rate',
                   'Total_Population','Dog_Market_Size','Dog_Annual_Consumption']

cat_future_features = predict_future_features(df,cat_future_data,future_years)
dog_future_features = predict_future_features(df,dog_future_data,future_years)

#创建未来模型预测的数据框
future_cat_df = pd.DataFrame({
    'Year': future_years,
    'GDP_Per_Capita':cat_future_features['GDP_Per_Capita'] ,
    'Urbanization_Rate':cat_future_features['Urbanization_Rate'],
    'Total_Population':cat_future_features['Total_Population'],
    'Cat_Market_Size':cat_future_features['Cat_Market_Size'],
    'Cat_Annual_Consumption':cat_future_features['Cat_Annual_Consumption']
})

future_dog_df = pd.DataFrame({
    'Year': future_years,
    'GDP_Per_Capita':dog_future_features['GDP_Per_Capita'] ,
    'Urbanization_Rate':dog_future_features['Urbanization_Rate'],
    'Total_Population':dog_future_features['Total_Population'],
    'Dog_Market_Size':dog_future_features['Dog_Market_Size'],
    'Dog_Annual_Consumption':dog_future_features['Dog_Annual_Consumption']
})

#使用最佳模型进行预测
cat_predictions = best_cat_model.predict(future_cat_df)
dog_predictions = best_dog_model.predict(future_dog_df)
#评估模型性能
cat_train_pred = best_cat_model.predict(x_cat)
dog_train_pred = best_dog_model.predict(x_dog)

cat_mse = mean_squared_error(y_cat,cat_train_pred)
cat_mae = mean_absolute_error(y_cat,cat_train_pred)
cat_r2 = r2_score(y_cat,cat_train_pred)

dog_mse = mean_squared_error(y_dog,dog_train_pred)
dog_mae = mean_absolute_error(y_dog,dog_train_pred)
dog_r2 = r2_score(y_dog,dog_train_pred)

print("\n模型评估指标：")
print(f"宠物猫模型-MSE：{cat_mse:.2f},MAE:{cat_mae:.2f},R2:{cat_r2:.2f}")
print(f"宠物狗模型-MSE：{dog_mse:.2f},MAE:{dog_mae:.2f},R2:{dog_r2:.2f}")

#输出未来预测结果
print("\n未来三年宠物数量预测：")
for year,cat_pred,dog_pred in zip(future_years,cat_predictions,dog_predictions):
    print(f"年份{year}:预测宠物猫数量：{cat_pred:.2f}万只，预测宠物狗数量：{dog_pred:.2f}万只")

#将图形可视化
sns.set_theme(style='whitegrid')
def plot_actual_vs_predicted(years,actual,predicted,title):
    plt.figure(figsize=(8,8))
    plt.plot(years,actual,label='Actual',marker='o')
    plt.plot(years,predicted, label='Predicted', marker='s')
    plt.title('Comparison of actual and forecasted results')
    plt.xlabel('Year')
    plt.ylabel('Number of Pets(in 10.000s)')
    plt.legend()
    plt.grid(True)
    plt.show()

plot_actual_vs_predicted(df['Year'],y_cat,cat_train_pred,'Cat_Actual vs Predicted')
plot_actual_vs_predicted(df['Year'],y_dog,dog_train_pred,'Dog_Actual vs Predicted')













